<html>
  <head>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <meta name="theme-color" content="#008000"/>
   <title>exobot</title>
   <link rel="manifest" href="exobot_manifest.json">
   <script>
    if('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/exobot_sw.js')
        .then(function() {
              console.log('Service Worker Registered');
        });
    }
   </script>
    <style>
      body {
        margin: 0;
      }
    </style>
  </head>
  <body>
  <h1>exobot</h1>
  <script src="three.js"></script>
  <script src="GLTFLoader.js"></script>
  <script>
    let container, scene, camera, session, model;

    function init() {
      container = document.createElement('div');
      document.body.appendChild(container);

      scene = new THREE.Scene();
      scene.matrixAutoUpdate = false;
      // scene.background = new THREE.Color(0x3B3961);

      camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
      // camera.position.set(0, 1, 0);
      camera.lookAt(new THREE.Vector3());
      scene.add(camera);

      const ambientLight = new THREE.AmbientLight(0x808080);
      scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
      directionalLight.position.set(1, 1, 1);
      scene.add(directionalLight);

      {
        const loader = new THREE.GLTFLoader(); // .setPath( 'models/' );
        loader.load( 'exobot.glb', function ( o ) {

          o = o.scene;

          // o.position.z = -1;
          o.rotation.order = 'YXZ';
          o.scale.set(0.2, 0.2, 0.2);
          /* o.traverse(e => {
            e.castShadow = true;
          }); */

          /* o.quaternion.setFromUnitVectors(
            new THREE.Vector3(0, 0, -1),
            new THREE.Vector3(0, 0, 1)
          ); */
          o.updateMatrixWorld();
          // o.frustumCulled = false;
          for (let i = 0; i < o.children.length; i++) {
            o.children[i].frustumCulled = false;
          }

          model = o;

          scene.add(o);
          // scene.add(o.children[0]);
          // scene.add(o.children[0]);

        }, undefined, function ( e ) {

          console.error( e );

        } );
      }

      renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,
      });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);

      // window.browser.magicleap.RequestDepthPopulation(true);
      // renderer.autoClear = false;

      container.appendChild(renderer.domElement);

      renderer.setAnimationLoop(animate);
    }

    function animate(time, frame) {
      if (model) {
        const animationTime = 4000;
        const f = ((Date.now() % animationTime) / animationTime) * (Math.PI * 2);
        model.position.y = Math.sin(f) * 0.05;
        model.rotation.y = Math.sin(f*2) * Math.PI*2*0.05;
        model.rotation.z = Math.cos(f*2) * Math.PI*2*0.05;
        model.updateMatrixWorld();
      }

      renderer.render(scene, renderer.vr.enabled ? renderer.vr.getCamera(camera) : camera);
    }

    init();

    (async () => {
      console.log('request session');
      session = await navigator.xr.requestSession({
        exclusive: true,
      }).catch(err => Promise.resolve(null));

      if (session) {
        // console.log('request first frame');
        session.requestAnimationFrame((timestamp, frame) => {
          renderer.vr.setSession(session, {
            frameOfReferenceType: 'stage',
          });

          const {views} = frame.getViewerPose();
          const viewport = session.baseLayer.getViewport(views[0]);
          const width = viewport.width;
          const height = viewport.height;

          renderer.setSize(width * 2, height);

          renderer.setAnimationLoop(null);

          renderer.vr.enabled = true;
          renderer.vr.setAnimationLoop(animate);

          console.log('running!');
        });
      } else {
        console.log('no xr devices');
      }
    })();
  </script>
  </body>
</html>
